package com.gdou.controller;

import com.gdou.commons.Result;
import com.gdou.dto.AccountDto;
import com.gdou.model.Account;
import com.gdou.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private AccountService accountService;

    @GetMapping("/getAll")
    public Result getAll(){
        Result result = new Result();
        List<Account> accounts = accountService.findAll();

        result.setCode(200);
        result.setMsg("查询成功");
        result.setData(accounts);
        return result;
    }


    /*登录*/
    @PostMapping("/login")
    public Result login(@Valid AccountDto accountDto, BindingResult bindingResult, HttpSession session){
        /*判断是否有参数错误*/
        if (bindingResult.hasErrors()){
            return Result.DATA_FORMAT_ERROR;
        }
        return accountService.findLogin(accountDto,session);
    }


    @RequestMapping("/logout")
    public Result logout(HttpSession session){

        session.invalidate();

        return Result.SUCCESS;
    }

    /*账户列表*/
    @RequestMapping("/getAccountsByPage")
    public Result getAccountsByPage(@RequestParam(required = false,defaultValue = "1") Integer pageNum,
                                    @RequestParam(required = false,defaultValue = "10") Integer pageSize){

        return accountService.findAccountsByPage(pageNum,pageSize);

    }
    /*修改账户的状态
    * 超级管理员 不可以禁用(得判断 当前登录账户 是否是超级管理员)
    * */
    @PostMapping("/editAccountStatus")
    public Result editAccountStatus(Integer status,Long id,HttpSession session){
        return accountService.modifyAccountStatus(status,id,session);
    }

    /*重置密码  默认密码123456*/
    @PostMapping("/editRestAccountPwd")
    public Result editRestAccountPwd(Long id,HttpSession session){
        return accountService.modifyRestyAccountPwd(id,session);
    }

    /*删除账户*/
    @PostMapping("/cutOneAccount")
    public Result cutOneAccount(Long id,HttpSession session){
        return accountService.removeOneAccountById(id,session);
    }

    /*添加账户  默认密码为123456  */
    @PostMapping("/addAccount")
    public Result addAccount(String username,HttpSession session){
        return accountService.saveAccount(username,session);
    }

    /*修改密码*/
    @PostMapping("/editAccountPwd")
    public Result editAccountPwd(String newPwd,HttpSession session){
        return accountService.modifyAccountPwd(newPwd,session);
    }



}